/**
 * 
 */
package cn.terrence.myoauth2.server.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;

/**
 * @author cuihua022
 * 资源生产Servlet
 */
public class ResourceBuilderServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2438539788029661743L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
           OAuthAccessResourceRequest resourceRequest = new OAuthAccessResourceRequest(request, ParameterStyle.HEADER);
           String accessToken = resourceRequest.getAccessToken();
           String id = request.getParameter("id");
           OAuthResponse r = OAuthRSResponse.status(HttpServletResponse.SC_OK)
        		             .setParam("info","你【"+accessToken+"】通过GET方式获取id为【"+id+"】的资源")
		                     .buildJSONMessage();
           response.setContentType("text/html;charset=utf-8");
		   response.setStatus(r.getResponseStatus());
		   PrintWriter pw = response.getWriter();
		   pw.print(r.getBody());
		   pw.flush();
		   pw.close();
		}catch(OAuthSystemException e){
			e.printStackTrace();
		}catch(OAuthProblemException ex) {
			ex.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			OAuthAccessResourceRequest resourceRequest = new OAuthAccessResourceRequest(request, ParameterStyle.HEADER);
            String accessToken = resourceRequest.getAccessToken();
            String id = request.getParameter("id");
            String name = request.getParameter("name");
            String address = request.getParameter("address");
            OAuthResponse r = OAuthRSResponse.status(HttpServletResponse.SC_OK)
        		             .setParam("info","你【"+accessToken+"】POST方式过来的信息为:【id="+id+",name="+name+",addreess="+address+"】")
		                     .buildJSONMessage();
            response.setContentType("text/html;charset=utf-8");
		    response.setStatus(r.getResponseStatus());
		    PrintWriter pw = response.getWriter();
		    pw.print(r.getBody());
		    pw.flush();
		    pw.close();
			}catch(OAuthSystemException e){
				e.printStackTrace();
			}catch(OAuthProblemException ex) {
				ex.printStackTrace();
			}
	}
	
	
}
